package com.lenovo.testreport.gray.web.languageTest.controller;

import com.lenovo.testreport.general.service.GeneralCaseService;
import com.lenovo.testreport.online.web.smoke.model.OnlineWebSmokeCase;
import com.lenovo.testreport.user.model.MessageCenter;
import com.lenovo.testreport.user.service.MessageService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author CJF
 * @date 2018/12
 * <p>
 * 对CASE表进行操作，取出错误日志，更新问题跟进状态，邮件发送
 */
@Controller
@RequestMapping("/gray/web")
public class
GrayWebDetailController {
    @Autowired
    @Qualifier("GrayWebLanguageEnglishPropertiesCaseService")
    private GeneralCaseService grayWebLanguageEnglishPropertiesCaseService;

    @Autowired
    private MessageService messageservice;

    //通过唯一的CID，查找每条CASE对应的日志
    @RequestMapping("/FindByCid")
    public @ResponseBody
    List<OnlineWebSmokeCase> FindByRid(HttpServletRequest request) {

        int id = Integer.valueOf(request.getParameter("cid"));
        List<OnlineWebSmokeCase> case1 = grayWebLanguageEnglishPropertiesCaseService.findByCid(request.getParameter("tablename"), id);
        return case1;

    }

    //通过唯一的CID，更新每条CASE的跟进状态
    @RequestMapping("/UpdateTrackBycid")
    public @ResponseBody
    String UpdateTrackBycid(HttpServletRequest request) {

        int id = Integer.valueOf(request.getParameter("cid"));
        List<OnlineWebSmokeCase> case1 = grayWebLanguageEnglishPropertiesCaseService.findByCid(request.getParameter("tablename"), id);
        OnlineWebSmokeCase update = new OnlineWebSmokeCase();
        for (OnlineWebSmokeCase temp : case1
                ) {
            update = temp;
        }
        update.setTrack(request.getParameter("track"));

        int result = grayWebLanguageEnglishPropertiesCaseService.modifycase(request.getParameter("tablename"), update);
        if (result > 0) {
            messageservice.AddMessageRecord(new MessageCenter(request.getSession().getAttribute("User").toString(), "新增了一条问题跟进", "question-normal"));
            return "提交成功！";
        } else {
            return "提交失败！";
        }
    }

    //通过CID来确认是某一条CASE，将CASE信息通过邮件发送给某人。
    @RequestMapping("/SendEmail")
    public @ResponseBody
    String SendEmail(HttpServletRequest request) throws AddressException, MessagingException {

        String emailsurl = request.getParameter("emailaddr");
        String tablename = request.getParameter("tablename");
        int cid = Integer.valueOf(request.getParameter("cid"));
        OnlineWebSmokeCase case1 = new OnlineWebSmokeCase();
        List<OnlineWebSmokeCase> cs = grayWebLanguageEnglishPropertiesCaseService.findByCid(tablename, cid);
        for (OnlineWebSmokeCase temp : cs
                ) {
            case1 = temp;
        }
        String[] emails = emailsurl.split(",");

        List list = new ArrayList();
        for (int i = 0; i < emails.length; i++) {
            list.add(new InternetAddress(emails[i]));
        }
        InternetAddress[] address = (InternetAddress[]) list.toArray(new InternetAddress[list.size()]);

        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// 连接协议
        properties.put("mail.smtp.host", "smtp.exmail.qq.com");// 主机名
        properties.put("mail.smtp.port", 465);// 端口号
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
        properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
        // 得到回话对象
        Session session = Session.getInstance(properties);
        // 获取邮件对象
        Message message = new MimeMessage(session);
        // 设置发件人邮箱地址
        message.setFrom(new InternetAddress("Chenjf@lenovocloud.com"));

        // 设置收件人邮箱地址
        //message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress(emailurl)});
        message.setRecipients(Message.RecipientType.TO, address);//一个收件人
        // 设置邮件标题
        StringBuffer strb = new StringBuffer();
        strb.append("");
        try {
            strb.append(case1.getDetail().substring(0, case1.getDetail().indexOf("测")));
            strb.append("测试");
        } catch (Exception e) {
        }

        message.setSubject("自动化运行失败Case:" + strb + "_" + case1.getModule() + "#" + case1.getMethod());
        // 设置邮件内容
        message.setText("模块：" + case1.getModule() + ",方法：" + case1.getMethod() + "，控制台信息：" + case1.getDetail() + "\n" + "备注:" + case1.getTrack());
        // 得到邮差对象
        Transport transport = session.getTransport();
        // 连接自己的邮箱账户
        transport.connect("Chenjf@lenovocloud.com", "Q13145241q");// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码

        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

        messageservice.AddMessageRecord(new MessageCenter(request.getSession().getAttribute("User").toString(), "指定了失败Case" + strb + "给" + emailsurl, "email-normal"));

        return "发送成功!";
    }
}
